package com.tanhua.dubbo.api;
import com.sun.org.apache.xerces.internal.util.XMLEntityDescriptionImpl;
import com.tanhua.domain.mg.FollowUser;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


@Service
public class FollowUserApiImpl implements FollowUserApi{

    //注入MongoTemplate对象
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     *  关注作者
     */
    @Override
    public void save(FollowUser followUser) {
        //补全信息
        followUser.setId(ObjectId.get());//设置主键
        followUser.setCreated(System.currentTimeMillis());//补全创建时间
        //插入数据
        mongoTemplate.save(followUser);
    }
    /**
     * 查询作者是否关注了这个当前用户
     */
    @Override
    public FollowUser queryFollowUserByTwoId(FollowUser followUser) {
        //获得followUser对象中的好友id  作者id
        Long userId = followUser.getUserId();
        Long followUserId = followUser.getFollowUserId();
        //创建查询条件
        Query query = new Query();
        query
                .addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("followUserId").is(followUserId));
        //根据查询条件来查询Mongo
        return mongoTemplate.findOne(query, FollowUser.class);
    }
    /**
     * 如果表中存在关注关系 那么就执行删除
     */
    @Override
    public void remove(FollowUser followUser) {
        //设置查询条件
        Query query = new Query();
        query.addCriteria(Criteria
                .where("userId").is(followUser.getUserId())
                .and("followUserId").is(followUser.getFollowUserId()));
        //调用删除方法
        mongoTemplate.remove(query,FollowUser.class);
    }
}
